/*
 * Copyright (C) 2011 Nanohex Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nanohexcorp.kudocode.snapqr;

import java.util.ArrayList;

import com.nanohexcorp.kudocode.snapqr.db.SimpleDB;
import com.nanohexcorp.kudocode.snapqr.object.QRLinksObject;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SnapQR extends ListActivity {
    private LayoutInflater mInflater;
    private ArrayList<QRLinksObject> mARQRLinksObject;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snapqr_main);
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        SimpleDB.initInstance(getApplicationContext());

		processAction();
        registerForContextMenu(getListView());
        setupButtons();
        loadListView();
    }

	private void processAction()
	{
		Bundle extras = getIntent().getExtras();
		if(extras == null) return;
		String action = extras.getString("action");
		if(action == null) return;

		if(action.equals("scan")) {
			startBarcodeScanner();
		}
	}

	private void setupButtons()
    {
        Button btnAbout = (Button) findViewById(R.id.bar_about);
        Button btnScan = (Button) findViewById(R.id.bar_scan);
        Button btnNew = (Button) findViewById(R.id.bar_new);

        btnAbout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startActivityForResult(new Intent(getApplicationContext(), SnapQRAbout.class), 0);
            }
        });

        btnScan.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	startBarcodeScanner();
            }
        });

        btnNew.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
        		Intent myIntent = new Intent(getApplicationContext(), SnapQRAdd.class);
                myIntent.putExtra("url", "");
                startActivityForResult(myIntent, 0);
            }
        });
    }

	private void startBarcodeScanner()
	{
		if(IntentIntegrator.initiateScan(this) != null)
		{
			 AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
			 downloadDialog.setTitle(R.string.scanner_title);
			 downloadDialog.setMessage(R.string.scanner_message);
			 downloadDialog.setPositiveButton(R.string.scanner_download, new DialogInterface.OnClickListener() {
				 public void onClick(DialogInterface dialogInterface, int i) {
					 Uri uri = Uri.parse(getString(R.string.scanner_appuri));
					 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					 startActivity(intent);
				 }
			 });
			 downloadDialog.setNegativeButton(R.string.scanner_cancel, new DialogInterface.OnClickListener() {
				 public void onClick(DialogInterface dialogInterface, int i) {}
			 });
			 downloadDialog.show();
		}
	}

    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    	if(resultCode != RESULT_OK) return;
    	if(requestCode == IntentIntegrator.REQUEST_CODE) {
    		IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    		if (scanResult != null) {
    			String out = scanResult.getContents();
    			if ((out != null) && (out.contains("http"))) {
            		Intent myIntent = new Intent(getApplicationContext(), SnapQRScanView.class);
                    myIntent.putExtra("url", out);
                    startActivityForResult(myIntent, 0);
    			}
    	    }
    	}
    }

    private void loadListView()
    {
    	mARQRLinksObject = SimpleDB.QRLinksTable.getAll();

    	ListView lv = (ListView)this.findViewById(android.R.id.list);
        lv.setAdapter(new ArrayAdapter<QRLinksObject>(this, R.layout.adaptor_content, mARQRLinksObject)
        	{
        		@Override
        		public View getView(int position, View convertView, ViewGroup parent) {
        			QRLinksObject obj = mARQRLinksObject.get(position);
        	    	obj.setUrl(obj.getUrl() + position);
        			View row;
        			if (null == convertView) {
        				row = mInflater.inflate(R.layout.adaptor_content, null);
        			} else {
        				row = convertView;
        			}
        			TextView tv = (TextView) row.findViewById(R.id.textLine);
        			tv.setText(getItem(position).getTitle());
        			return row;
        		}
        	}
        );
    }

    @Override
	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    }

    @Override
    public boolean onContextItemSelected (MenuItem item)
    {
        AdapterView.AdapterContextMenuInfo info;
    	try {
    	    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    	} catch (ClassCastException e) {
    	    return false;
    	}
    	QRLinksObject qrLinksObject = mARQRLinksObject.get((int)info.position);

		switch (item.getItemId()) {
	    	case R.id.export_record:
		    	Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
		        intent.addCategory(Intent.CATEGORY_DEFAULT);
		        intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
		        intent.putExtra("ENCODE_DATA",qrLinksObject.getUrl());
		        startActivity(intent);
	    		break;
    	    case R.id.edit_record:
        		Intent myIntent = new Intent(getApplicationContext(), SnapQREdit.class);
                myIntent.putExtra("id", qrLinksObject.getID());
                startActivityForResult(myIntent, 0);
                break;
    	    case R.id.delete_record:
    	    	SimpleDB.QRLinksTable.remove(qrLinksObject);
    	    	loadListView();
    	    	break;
    	    case R.id.cancel_record:
    	    	break;
    	    default:
    	        return super.onOptionsItemSelected(item);
		}
    	return true;
    }

    @Override
    protected void onListItemClick(ListView list, View view, int position, long id) {
    	super.onListItemClick(list, view, position, id);
    	QRLinksObject qrLinksObject = (QRLinksObject) list.getItemAtPosition(position);

    	Intent myIntent = new Intent(view.getContext(), SnapQRView.class);
        myIntent.putExtra("id", qrLinksObject.getID());
        startActivityForResult(myIntent, 0);
    }
}